<?php
namespace app\user_api\controller;

use tp5_lib\api\controller\ApiBaseController;
use tp5_lib\user\model\UserModel;
use app\user\service\UserService;
use tp5_lib\user\validate\UserValidate;
use tp5_lib\user\logic\UserLogic;
use think\facade\Session;

/**
 * 用户相关的接口
 * @property UserModel $model 用户模型
 * @property UserLogic $logic 用户逻辑
 * @property UserValidate $validate 用户验证器
 */
class UserController extends ApiBaseController
{
    public function __get($name)
    {
        if($name === "model"){
            if(empty($this->_model)){
                $this->_model=new UserModel();
            }
            return $this->_model;
        }
        elseif($name === "logic"){
            if(empty($this->_logic)){
                $this->_logic=new UserLogic();
            }
            return $this->_logic;
        }
        elseif($name === "validate"){
            if(empty($this->_validate)){
                $this->_validate=new UserValidate();
            }
            return $this->_validate;
        }
    }
    public function _empty($name)
    {
        $user=$this->checkLogin();
        $methods=get_class_methods(UserService::class);
        foreach($methods as $method){
            if(strtolower($name) === strtolower($method)){
                $service=new UserService();
                $result=call_user_func([$service,$method],$user,$_REQUEST);
                if(!$result){
                    $this->error($service->getError());
                }
                $this->success();
            }
        }
        $this->error("未定义的操作");
    }
    /**
     * 查找用户
     */
    public function search()
    {
        $data=$_REQUEST;
        $um=new UserModel();
        $query=$um->db();

        $equal_fields=["id","username"];
        foreach($data as $key => $item){
            if(in_array($key,$equal_fields)){
                $query->where($key,$item);
            }
        }

        $like_fields=["nickname","mobile"];
        foreach($data as $key => $item){
            if(in_array($key,$like_fields)){
                $query->whereLike($key,$item);
            }
        }

        $pagesize=isset($data["pagesize"])?$data["pagesize"]:20;
        $pagenum=isset($data["pagenum"])?$data["pagenum"]:1;
        $query->page($pagenum,$pagesize);

        $list=$query->field("id,username,nickname,mobile,create_time")->select();
        if(!$list){
            $this->error($um->getError());
        }
        $this->result($list,1);
    }
    /**
     * 获取当前用户的信息
     */
    public function info()
    {
        $user=$this->checkLogin();
        $model=new UserModel();
        if(!$user=$model->where(["id"=>$user["id"]])->find()){
            Session::clear("user");
            $this->error("用户不存在");
        }
        else{
            Session::set("user",$user);
        }
        $this->result($user,1);
    }
    /**
     * 退出登录
     */
    public function logout()
    {
        Session::clear("user");
        $this->success();
    }
}
